package starfield.modpack.web;

import starfield.modpack.web.WebModpack;
import starfield.util.LogItem;
import java.awt.Toolkit;
import java.util.List;
import java.util.concurrent.CancellationException;
import java.util.concurrent.ExecutionException;
import java.util.logging.Level;
import javax.swing.SwingWorker;
import starfield.ui.SyncingDialog;

public abstract class SyncingTask extends SwingWorker<Void, LogItem> {
	protected WebModpack modpack;
	private SyncingDialog dialog;
	private boolean silent;

	public SyncingTask(WebModpack modpack, boolean silent) {
		this.modpack = modpack;
		this.silent = silent;
		dialog = new SyncingDialog(null, true, this);
	}
	
	@Override
	protected void process(List<LogItem> chunks) {
		for (LogItem chunk : chunks) {
			dialog.log(chunk.getMessage(), chunk.getLevel());
		}
	}
	
	@Override
	public void done() {
		try {
			Toolkit.getDefaultToolkit().beep();
			get();
		} catch (ExecutionException ex) {
			dialog.log(ex.getCause().getMessage(), Level.SEVERE);
		} catch (InterruptedException ex) {
			dialog.log(ex.getMessage(), Level.SEVERE);
		} catch (CancellationException ex) {
			dialog.log("Syncing cancelled.", Level.SEVERE);
		}
		
		dialog.getOkButton().setEnabled(true);
		dialog.getCancelButton().setEnabled(false);
	}
	
	protected final void publish(Object message, Level level) {
		publish(new LogItem(message, level));
	}
	
	public void showDialog() {
		dialog.clearLog();
		dialog.getOkButton().setEnabled(false);
		dialog.getCancelButton().setEnabled(true);
		
		if (!silent) {
			dialog.setVisible(true);
		}
	}

	public WebModpack getModpack() {
		return modpack;
	}

	public SyncingDialog getDialog() {
		return dialog;
	}

	public boolean isSilent() {
		return silent;
	}
}
